package unit04.day06;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
	/*
	 * java.net.Socket
	 * 封装了TCP协议，使用它就可以基于TCP协议进行网络通讯
	 * Socket是运行在客户端的
	 * */
	private Socket socket;

	//初始化客户端,若远程服务器没响应就抛出异常
	public Client() throws Exception{
		System.out.println("正在连接服务端...");
//		socket = new Socket("58.51.141.218",9049);
		socket = new Socket("localhost",9049);
		System.out.println("已与服务端建立连接");
	}
	//启动客户端
	public void start() {
		try {
			Scanner scan = new Scanner(System.in);
			
			/*先输一个昵称
			 * */
			String username = null;
			while(true) {
				System.out.println("请输入昵称");
				username = scan.nextLine();
				if(username.length() >= 0) {
					break;
				}
			}
			
			//Socket提供方法OutputStream getOutputStream获取一个字节输出流，通过该流写出的数据会被发送至远端计算机
			OutputStream out = socket.getOutputStream();
			
			OutputStreamWriter osw = new OutputStreamWriter(out,"UTF-8");
			
			PrintWriter pw = new PrintWriter(osw,true);
			
			//先将昵称发送服务器
			pw.println(username);
			
			/*启动读取服务端发送过来的消息线程*/
			ServerHandler handler = new ServerHandler();
			Thread t= new Thread(handler);
			t.start();
			
			
			//将字符串发送至服务端
//			pw.println("你好服务端!");
			while(true) {
				System.out.println("请输入聊天内容");
				String userPrint = scan.next();
				pw.println(userPrint);
			}
			  
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			Client client = new Client();
			client.start();
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("客户端启动失败");
		}
	}
	
	//该线程用来读取服务端发送过来的消息并输出到客户端控制台显示
	
	class ServerHandler implements Runnable{
		
		@Override
		public void run() {
			try {
				//接受服务端发送的信息
				InputStream in = socket.getInputStream();
				
				InputStreamReader isr = new InputStreamReader(in,"UTF-8");
				
				BufferedReader br = new BufferedReader(isr);
				
				String message = null;
				
				while((message = br.readLine()) != null) {
					System.out.println(message);
				}
			}catch(Exception e) {
			
			}
		}
		
	}
}
